package org.jash.ting13.book

import android.widget.Toast
import androidx.annotation.OptIn
import androidx.lifecycle.lifecycleScope
import androidx.media3.common.MediaItem
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.MediaSession
import kotlinx.coroutines.launch
import org.jash.ting13.databinding.ActivityBookBinding
import org.jash.utils.Event
import org.jash.utils.log
import org.jash.utils.mvi.BaseActivity

class BookActivity : BaseActivity<ActivityBookBinding, BookViewModel>() {
    lateinit var url:String
    lateinit var adapter: ChapterAdapter
    lateinit var player:ExoPlayer
    @OptIn(UnstableApi::class) override fun initData() {
        url = intent.getStringExtra("url") ?: ""
        adapter = ChapterAdapter()
        player = ExoPlayer.Builder(this).build()
        viewModel.state.observe(this) {
            when(it) {
                is BookState.Success -> binding.book = it.book
                is BookState.Play -> {
                    val mediaItem = MediaItem.fromUri(it.url)
                    player.addMediaItem(mediaItem)

                    player.prepare()
                    val session = MediaSession.Builder(this, player)
                        .setId("uniqueSessionId")
                        .build()
                    player.play()
                    binding.playControl.show()
                }
                is BookState.Paging -> {
                    lifecycleScope.launch {
                        adapter.submitData(it.data)
                    }
                }
                is BookState.Failure -> Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()

            }
        }
        viewModel.intent.trySend(BookIntent.LoadDetail(url))
    }

    @OptIn(UnstableApi::class)
    override fun initView() {
        binding.recycler.adapter = adapter
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
//        val mediaItem = MediaItem.fromUri("")
//        player.addMediaItem(mediaItem)
//        player.prepare()

        binding.playControl.player = player
    }
    @Event("loadPlay")
    fun loadPlay(src:String) {
        viewModel.intent.trySend(BookIntent.LoadPlay(src))
    }

}